package com.bawei.module_video_hall.ui


import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_mvi.Router
import com.bawei.lib_common.base.utils.LoggerUtils

import com.bawei.lib_common.entity.SimpleVideoEntityItem
import com.bawei.lib_mvi.base.BaseMVIFragment
import com.bawei.lib_storage.mmkv.AuthMMKV
import com.bawei.module_video_hall.VideoItemCache
import com.bawei.module_video_hall.adapter.VideoHallAdapter
import com.bawei.module_video_hall.adapter.VideoHallTypeAdapter
import com.bawei.module_video_hall.databinding.FragmentVideoHallBinding
import com.bawei.module_video_hall.mvi.intent.VideoHallIntent
import com.bawei.module_video_hall.mvi.model.MultiTypeModelItem
import com.bawei.module_video_hall.mvi.model.RecommendVideoModelItem
import com.bawei.module_video_hall.mvi.state.VideoHallState
import com.bawei.module_video_hall.mvi.viewmodel.VideoHallViewModel
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.coroutines.launch


class VideoHallFragment : BaseMVIFragment() {

    private lateinit var mViewModel: VideoHallViewModel

    lateinit var binding: FragmentVideoHallBinding


    private var dataSource: MutableList<MultiTypeModelItem> = mutableListOf()

    private var videoDataSource: List<RecommendVideoModelItem> = mutableListOf()

    lateinit var mVideoAdapter: VideoHallAdapter

    private var pageIndex = 1
    private var pageSize = 10
    private var currentSelectedPosition = 0 // 当前选中的分类位置
    private var currentTypeId = 0 // 当前分类的ID
    private var currentSort: String? = null // 当前排序方式

    private val mAdapter: VideoHallTypeAdapter by lazy {
        VideoHallTypeAdapter(dataSource.toMutableList(), onItemClick = { i, typeId ->
            currentSelectedPosition = i
            pageIndex = 1 // 重置页码
            Log.d("VideoHallFragment", "onItemClick: position=$i, typeId=$typeId")
            mAdapter.setSelectedPosition(i) // 更新选中状态
            lifecycleScope.launch {
                if (i == 0) {
                    currentTypeId = 0 // 推荐分类的ID为0
                    mViewModel.intents.send(VideoHallIntent.GetRecommendVideo(pageIndex, pageSize))
                } else {
                    currentTypeId = (dataSource[i].id) + 19
                    Log.d("VideoHallFragment", "Selected type ID: $currentTypeId")
                    mViewModel.intents.send(
                        VideoHallIntent.GetMultiVideoByTypeId(
                            pageIndex,
                            pageSize,
                            currentTypeId
                        )
                    )
                }
            }
        })
    }


    override fun generateViewModel() {
        mViewModel = ViewModelProvider(this)[VideoHallViewModel::class.java]
    }

    override fun getFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentVideoHallBinding.inflate(inflater, container, false)
        return binding.root;
    }

    override fun lazyLoad() {
        lifecycleScope.launchWhenStarted {
            mViewModel.intents.send(VideoHallIntent.GetMultiType)
            mViewModel.intents.send(VideoHallIntent.GetRecommendVideo(pageIndex, pageSize))
        }
    }

    override fun initView() {
        super.initView()

        //添加下拉刷新监听
        binding.videoHallSrl.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                Log.d("VideoHallFragment", "onRefresh triggered")
                pageIndex = 1
                refreshOrMoreList()
                refreshLayout.finishRefresh()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                Log.d("VideoHallFragment", "onLoadMore triggered")
                pageIndex++
                refreshOrMoreList()
                refreshLayout.finishLoadMore()
            }

        })

        // 设置筛选按钮点击事件
        binding.videoHallFilterIv.setOnClickListener {
            toggleFilterMenu()
        }

        // 设置筛选选项点击事件
        binding.tvFilterAll.setOnClickListener {
            applyFilter(null)
            hideFilterMenu()
        }

        binding.tvFilterLatest.setOnClickListener {
            applyFilter("latest")
            hideFilterMenu()
        }

        binding.tvFilterHot.setOnClickListener {
            applyFilter("hot")
            hideFilterMenu()
        }

        // 点击外部区域隐藏筛选菜单
        binding.root.setOnClickListener {
            if (binding.cardFilterMenu.visibility == View.VISIBLE) {
                hideFilterMenu()
            }
        }

        // 初始化筛选选项的视觉状态
        updateFilterOptionStates(currentSort)

        binding.rvVideoHallType.layoutManager =
            LinearLayoutManager(requireActivity(), LinearLayoutManager.HORIZONTAL, false)
        binding.rvVideoHallType.adapter = mAdapter


        binding.rvVideoHall.run {
            setItemViewCacheSize(12) //设置屏幕外ViewHolder缓存数量，默认为2
            setHasFixedSize(true) //减少固定大小的子组件反复测量
            setRecycledViewPool(RecyclerView.RecycledViewPool().apply {
                setMaxRecycledViews(0, 10) //根据不同的组件类型缓存
            })
            setViewCacheExtension(VideoItemCache(binding.rvVideoHall)) //自定义缓存

            //滚动时停止图片加载
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        Glide.with(this@VideoHallFragment).resumeRequests()
                    } else {
                        Glide.with(this@VideoHallFragment).pauseRequests()
                    }
                }
            })

            //关闭不必要动画
            (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false

            //设置布局管理器和数据适配器
            mVideoAdapter = VideoHallAdapter(
                videoDataSource.toMutableList(),
                lifecycleScope,
                AuthMMKV.uId.toString(),
                onItemClick = { videoItem ->
                    // 将RecommendVideoModelItem转换为SimpleVideoEntityItem
                    val simpleVideoEntity = convertToSimpleVideoEntity(videoItem)
                    // 跳转到详情页
                    ARouter.getInstance()
                        .build(Router.Ui.VIDEOETAIL_Actvivty)
                        .withSerializable("videoItem", simpleVideoEntity)
                        .navigation()
                }
            )
            binding.rvVideoHall.layoutManager = GridLayoutManager(requireContext(), 2)
            binding.rvVideoHall.adapter = mVideoAdapter
        }

        // 初始化红包组件
        binding.redPacketWidget.setStateCallback(object :
            com.bawei.lib_common.widget.RedPacketWidget.StateCallback {
            override fun completed() {
                ToastUtils.showShort("红包动画完成，恭喜获得红包！")
                // 设置红包数量
                binding.redPacketWidget.setTvNum(99)
                // 这里可以添加红包领取逻辑
            }

            override fun onRandomRedPacketGenerated(amount: Int) {
                Log.d("VideoHallFragment", "随机红包生成：+$amount")
                ToastUtils.showShort("恭喜获得随机红包：+$amount")
                // 这里可以添加随机红包的处理逻辑
                // 比如保存到数据库、显示通知等
            }
        })

        // 移除红包组件点击事件，只通过滑动触发

        // 添加RecyclerView滑动监听
        setupScrollListener()
    }

    /**
     * 设置滑动监听
     */
    private fun setupScrollListener() {
        // 为视频列表添加滑动监听
        binding.rvVideoHall.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                when (newState) {
                    RecyclerView.SCROLL_STATE_IDLE -> {
                        // 停止滑动
                        binding.redPacketWidget.onScrollStop()
                        Log.d("VideoHallFragment", "视频列表停止滑动，红包动画停止")
                    }

                    RecyclerView.SCROLL_STATE_DRAGGING -> {
                        // 开始滑动
                        binding.redPacketWidget.onScrollStart()
                        Log.d("VideoHallFragment", "视频列表开始滑动，红包动画开始")
                    }

                    RecyclerView.SCROLL_STATE_SETTLING -> {
                        // 惯性滑动
                        binding.redPacketWidget.onScrollStart()
                        Log.d("VideoHallFragment", "视频列表惯性滑动，红包动画继续")
                    }
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                // 滑动过程中
                if (dx != 0 || dy != 0) {
                    Log.d("VideoHallFragment", "检测到滑动: dx=$dx, dy=$dy")
                    binding.redPacketWidget.onScroll()
                }
            }
        })

        // 为类型列表添加滑动监听
        binding.rvVideoHallType.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                when (newState) {
                    RecyclerView.SCROLL_STATE_IDLE -> {
                        // 停止滑动
                        binding.redPacketWidget.onScrollStop()
                        Log.d("VideoHallFragment", "类型列表停止滑动，红包动画停止")
                    }

                    RecyclerView.SCROLL_STATE_DRAGGING -> {
                        // 开始滑动
                        binding.redPacketWidget.onScrollStart()
                        Log.d("VideoHallFragment", "类型列表开始滑动，红包动画开始")
                    }

                    RecyclerView.SCROLL_STATE_SETTLING -> {
                        // 惯性滑动
                        binding.redPacketWidget.onScrollStart()
                        Log.d("VideoHallFragment", "类型列表惯性滑动，红包动画继续")
                    }
                }
            }


            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                // 滑动过程中
                if (dx != 0 || dy != 0) {
                    Log.d("VideoHallFragment", "检测到滑动: dx=$dx, dy=$dy")
                    binding.redPacketWidget.onScroll()
                }
            }
        })
    }


    /**
     * 切换筛选菜单的显示/隐藏
     */
    private fun toggleFilterMenu() {
        if (binding.cardFilterMenu.visibility == View.VISIBLE) {
            hideFilterMenu()
        } else {
            showFilterMenu()
        }
    }

    /**
     * 显示筛选菜单
     */
    private fun showFilterMenu() {
        binding.cardFilterMenu.visibility = View.VISIBLE
        Log.d("VideoHallFragment", "Filter menu shown")
    }

    /**
     * 隐藏筛选菜单
     */
    private fun hideFilterMenu() {
        binding.cardFilterMenu.visibility = View.GONE
        Log.d("VideoHallFragment", "Filter menu hidden")
    }

    /**
     * 应用筛选
     */
    private fun applyFilter(sort: String?) {
        currentSort = sort
        Log.d("VideoHallFragment", "Applying filter: $sort")

        // 更新筛选选项的视觉状态
        updateFilterOptionStates(sort)

        // 显示筛选状态
        val filterText = when (sort) {
            "latest" -> "最新"
            "hot" -> "最热"
            else -> "全部"
        }

        // 对当前数据进行排序
        sortCurrentData(sort)
    }

    /**
     * 对当前数据进行排序
     */
    private fun sortCurrentData(sort: String?) {
        if (videoDataSource.isEmpty()) {
            Log.d("VideoHallFragment", "No data to sort")
            return
        }

        Log.d("VideoHallFragment", "Sorting ${videoDataSource.size} items by: $sort")

        val sortedList = when (sort) {
            "latest" -> {
                // 按ctime排序，最新的在前面
                val sorted = videoDataSource.sortedByDescending { item ->
                    try {
                        // 尝试解析ctime，支持多种格式
                        val ctime = when {
                            item.ctime.matches(Regex("\\d+")) -> {
                                // 如果是纯数字，直接转换为Long
                                item.ctime.toLongOrNull() ?: 0L
                            }

                            item.ctime.matches(Regex("\\d{4}-\\d{2}-\\d{2}.*")) -> {
                                // 如果是日期格式，转换为时间戳
                                val formatter = java.text.SimpleDateFormat(
                                    "yyyy-MM-dd HH:mm:ss",
                                    java.util.Locale.getDefault()
                                )
                                try {
                                    formatter.parse(item.ctime)?.time ?: 0L
                                } catch (e: Exception) {
                                    Log.e(
                                        "VideoHallFragment",
                                        "Error parsing date format: ${item.ctime}",
                                        e
                                    )
                                    0L
                                }
                            }

                            else -> {
                                Log.w(
                                    "VideoHallFragment",
                                    "Unknown ctime format: ${item.ctime}"
                                )
                                0L
                            }
                        }
                        Log.d(
                            "VideoHallFragment",
                            "Item ${item.id}: ctime=${item.ctime}, parsed=$ctime"
                        )
                        ctime
                    } catch (e: Exception) {
                        Log.e("VideoHallFragment", "Error parsing ctime: ${item.ctime}", e)
                        0L
                    }
                }
                Log.d(
                    "VideoHallFragment",
                    "Sorted by latest, first item ctime: ${sorted.firstOrNull()?.ctime}"
                )
                sorted
            }

            "hot" -> {
                // 按favoritecount排序，点赞数多的在前面
                val sorted = videoDataSource.sortedByDescending { item ->
                    Log.d(
                        "VideoHallFragment",
                        "Item ${item.id}: favoritecount=${item.favoritecount}"
                    )
                    item.favoritecount
                }
                Log.d(
                    "VideoHallFragment",
                    "Sorted by hot, first item favoritecount: ${sorted.firstOrNull()?.favoritecount}"
                )
                sorted
            }

            else -> {
                // 保持原始顺序
                Log.d("VideoHallFragment", "Keeping original order")
                videoDataSource
            }
        }

        // 在协程中更新适配器数据
        lifecycleScope.launch {
            mVideoAdapter.setData(sortedList.toMutableList())
            Log.d(
                "VideoHallFragment",
                "Data sorted by: $sort, items count: ${sortedList.size}"
            )
        }
    }

    /**
     * 更新筛选选项的视觉状态
     */
    private fun updateFilterOptionStates(selectedSort: String?) {
        // 重置所有选项的颜色
        binding.tvFilterAll.setTextColor(resources.getColor(android.R.color.black, null))
        binding.tvFilterLatest.setTextColor(resources.getColor(android.R.color.black, null))
        binding.tvFilterHot.setTextColor(resources.getColor(android.R.color.black, null))

        // 设置选中选项的颜色
        val selectedColor = resources.getColor(android.R.color.holo_blue_dark, null)
        when (selectedSort) {
            null -> binding.tvFilterAll.setTextColor(selectedColor)
            "latest" -> binding.tvFilterLatest.setTextColor(selectedColor)
            "hot" -> binding.tvFilterHot.setTextColor(selectedColor)
        }
    }

    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED) {
                mViewModel.multiTypeFlow.collect {
                    when (it) {
                        is VideoHallState.Empty -> {
                            ToastUtils.showLong("数据为空")
                        }

                        is VideoHallState.Failed -> {
                            LoggerUtils.d("TAG", "错误信息：" + it.msg)
                        }

                        is VideoHallState.Init -> {

                        }

                        is VideoHallState.VideoTypeSuccess -> {
                            dataSource = it.list!!.toMutableList()
                            dataSource.add(0, MultiTypeModelItem("0", 0, 0, 0, "0", "推荐"))
                            mAdapter.setData(dataSource)
                            mAdapter.setSelectedPosition(0) // 默认选中第一个（推荐）
                            currentSelectedPosition = 0 // 设置初始选中位置
                            currentTypeId = 0 // 设置初始分类ID为推荐
                            Log.d(
                                "VideoHallFragment",
                                "Initial setup: currentSelectedPosition=$currentSelectedPosition, currentTypeId=$currentTypeId"
                            )
                        }

                        else -> {}
                    }
                }
            }

        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED) {
                mViewModel.videoHallFlow.collect {
                    Log.d("VideoHallFragment", "videoHallFlow received: $it")
                    when (it) {
                        is VideoHallState.Empty -> {
                            ToastUtils.showLong("数据为空")
                        }

                        is VideoHallState.Failed -> {
                            LoggerUtils.d("TAG", "错误信息：" + it.msg)
                            // 如果是加载更多失败，回退页码
                            if (pageIndex > 1) {
                                pageIndex--
                                android.util.Log.d(
                                    "VideoHallFragment",
                                    "Load more failed, rollback pageIndex to $pageIndex"
                                )
                            }
                        }

                        is VideoHallState.Init -> {

                        }

                        is VideoHallState.VideoRecommendSuccess -> {
                            android.util.Log.d(
                                "VideoHallFragment",
                                "VideoRecommendSuccess: pageIndex=$pageIndex, dataSize=${it.list?.size}"
                            )
                            if (pageIndex == 1) {
                                videoDataSource = it.list!!
                                android.util.Log.d(
                                    "VideoHallFragment",
                                    "Setting new data: ${videoDataSource.size} items"
                                )
                                // 应用当前筛选
                                if (currentSort != null) {
                                    sortCurrentData(currentSort)
                                } else {
                                    lifecycleScope.launch {
                                        mVideoAdapter.setData(videoDataSource)
                                    }
                                }
                            } else {
                                android.util.Log.d(
                                    "VideoHallFragment",
                                    "Adding more data: ${it.list?.size} items"
                                )
                                // 添加新数据后重新排序
                                val newData = videoDataSource.toMutableList()
                                newData.addAll(it.list!!)
                                videoDataSource = newData

                                if (currentSort != null) {
                                    sortCurrentData(currentSort)
                                } else {
                                    lifecycleScope.launch {
                                        mVideoAdapter.addData(it.list!!)
                                    }
                                }
                            }
                        }

                        else -> {}
                    }
                }
            }

        }

    }

    override fun initEvent() {
        super.initEvent()
    }


    private fun refreshOrMoreList() {
        android.util.Log.d(
            "VideoHallFragment",
            "refreshOrMoreList: currentSelectedPosition=$currentSelectedPosition, currentTypeId=$currentTypeId, pageIndex=$pageIndex, sort=$currentSort"
        )
        lifecycleScope.launch {
            if (currentSelectedPosition == 0) {
                // 推荐分类
                mViewModel.intents.send(VideoHallIntent.GetRecommendVideo(pageIndex, pageSize))
            } else {
                // 其他分类
                mViewModel.intents.send(
                    VideoHallIntent.GetMultiVideoByTypeId(
                        pageIndex,
                        pageSize,
                        currentTypeId
                    )
                )
            }
        }
    }

    override fun onResume() {
        super.onResume()
        Log.d("VideoHallFragment", "onResume called")

        // 延迟刷新收藏状态，确保数据库完全初始化
        lifecycleScope.launch {
            kotlinx.coroutines.delay(500) // 延迟500ms
            refreshFavoriteStatus()
        }
    }

    // 刷新收藏状态的方法
    private suspend fun refreshFavoriteStatus() {
        try {
            Log.d("VideoHallFragment", "Refreshing favorite status...")
            mVideoAdapter.refreshFavoriteStatus()
            Log.d("VideoHallFragment", "Favorite status refreshed successfully")
        } catch (e: Exception) {
            Log.e("VideoHallFragment", "Error refreshing favorite status", e)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        // 停止红包动画
        binding.redPacketWidget.stop()
    }

    /**
     * 将RecommendVideoModelItem转换为SimpleVideoEntityItem
     */
    private fun convertToSimpleVideoEntity(videoItem: RecommendVideoModelItem): SimpleVideoEntityItem {
        return SimpleVideoEntityItem(
            avatar_url = videoItem.avatar_url,
            channelid = "", // RecommendVideoModelItem中没有channelid字段，使用空字符串
            commentnum = 0, // RecommendVideoModelItem中没有commentnum字段，使用0
            ctime = videoItem.ctime,
            description = videoItem.description,
            group_id = videoItem.albumgroupid.toString(), // RecommendVideoModelItem中没有group_id字段，使用空字符串
            id = videoItem.id,
            image_url = videoItem.cover_url,
            item_id = "", // 使用id作为item_id
            labelIds = "", // RecommendVideoModelItem中没有labelIds字段，使用空字符串
            name = videoItem.name,
            playnum = 0, // RecommendVideoModelItem中没有playnum字段，使用0
            preview_url = videoItem.cover_url,
            publish_time = videoItem.ctime, // 使用ctime作为publish_time
            title = videoItem.title,
            userid = videoItem.userid,
            verifycode = videoItem.verifycode,
            videomainimag = videoItem.videomainimag,
            videopath = videoItem.videopath
        )
    }

}